<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="优惠券名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="couponName">
              <j-popup
                v-model="model.couponName"
                field="couponName"
                org-fields="id,code"
                dest-fields="couponId,couponName"
                code="coupon_refer"
                :multi="false"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <j-popup
                v-model="model.customerName"
                field="customerName"
                org-fields="id,name"
                dest-fields="customerId,customerName"
                code="SelectorCustomer"
                :multi="true"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发放数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="issueNum">
              <a-input-number v-model="model.issueNum"  placeholder="请输入发放数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发放日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="issueDate">
              <j-date placeholder="请选择发放日期"  :value='defaultValue' :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'CouponCustomerForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/coupon/couponCustomer/add",
          edit: "/coupon/couponCustomer/edit",
          queryById: "/coupon/couponCustomer/queryById",
          sendMsgUrl:"/sys/api/sendWebSocketMsgPost"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      defaultValue() {
        if (!this.model.billDate) {
          // 当 `this.model.billDate` 不存在时，返回当前日期时间（年月日时分秒）
          return new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
          });
        } else {
          // 当 `this.model.billDate` 存在时，将其转换为年月日时分秒格式的字符串
          const isoDateTime = this.model.billDate.toISOString();
          return isoDateTime.replace('T', '-').slice(0, -5);
        }
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                this.sendMsg()
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })



      },
      popupCallback(value,row){
         this.model = Object.assign(this.model, row);
      },

      sendMsg(){

        let datas = {
          userIds:[this.model.customerId],
          msg:{
            type: "优惠券",
            id: this.model.couponId,
            content: "您有新的优惠券待领取"
          }
        }
        console.log(datas)
        //发放优惠券成功之后发送消息
        postAction(this.url.sendMsgUrl,datas).then((res)=>{
          if(res.success){
            this.$message.success(res.message);
            this.$emit('ok');
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    }
  }
</script>